package com.shisfish.library.Timing;

import java.util.ArrayList;
import java.util.List;
import java.util.TimerTask;

import com.shisfish.library.Impl.BookLoanImpl;
import com.shisfish.library.Impl.BookMessageImpl;
import com.shisfish.library.Impl.LoanRemindImpl;
import com.shisfish.library.Model.BookLoan;
import com.shisfish.library.Model.BookMessage;
import com.shisfish.library.Model.LoanRemind;

public class SortLoan extends TimerTask {

	@Override
	public void run() {
		// TODO Auto-generated method stub
		
		// 找到未取消的，-----》单个isbn对应单个预约者
		List<BookLoan> bookLoans = new BookLoanImpl().selectByType(6);
		for (int i = 0; i < bookLoans.size() - 1; i++) {
			
			List<BookMessage> bookMessages = new BookMessageImpl().selectByKey(bookLoans.get(i).getIsbn());
			// 没有该书
			if (bookMessages.get(0).getIsBespeak() == 0) {
				bookLoans.remove(i);
				i --;
			} else {
				for (int j = 1; j < bookLoans.size(); j++) {
					// 去掉重复的isbn（一个isbn只获取第一条数据）
					if (bookLoans.get(j).getIsbn().equals(bookLoans.get(i).getIsbn())) {
						bookLoans.remove(j);
						j --;
					}
				}
			}
			
		}
		
		// 把数据放到LoanRemind里（最终的需要存储的数据）
		List<LoanRemind> loanReminds = new ArrayList<LoanRemind>();
		for (int i = 0; i < bookLoans.size(); i++) {
			BookLoan bookLoan = bookLoans.get(i);
			if (bookLoan.getIsRemind() == 1) {
				// 去掉已经通知过的
				bookLoans.remove(i);
			}
			else {
				// 如果已有该条数据通知记录，则不需要再次添加
				List<LoanRemind> reminds = new LoanRemindImpl().selectByEMIS(bookLoan.getLoaner(), bookLoan.getIsbn());
				if (reminds.size() == 0) {
					LoanRemind loanRemind = new LoanRemind(bookLoan.getLoaner(), bookLoan.getIsbn());
					loanReminds.add(loanRemind);
				}
			}
		}
		if (loanReminds.size() > 0) {
			int flag = new LoanRemindImpl().insertAll(loanReminds);
			
			if (flag != 0) {
				System.out.println("预约通知记录已经添加好了！");
			}
		}
		else {
			System.out.println("没有需要预约通知的记录！");
		}
		
	}

}
